<template>
  <div :class="{'mobile-create-collect-report': showMobilePage}" class="create-collect-report">
    <div class="report-form">
      <el-form ref="editResouceForm" :model="dataForm" :rules="formRules" label-position="left" class="el-form-box-left" label-width="85px">
        <Title :title="title" class="mb-16" />
        <div class="form">
          <div class="flex-wrap" style="margin-right: 140px">
            <div class="one-cell">
              <el-form-item label="报表名称" prop="name" class="name">
                <el-input
                  v-model.trim="dataForm.name"
                  :disabled="isEdit && !isQuote"
                  maxlength="20"
                  size="small"
                  placeholder="请填写报表名称"
                  name="name"
                  type="text"/>
              </el-form-item>
              <el-form-item label="报表分类" prop="categoryId" class="client-type">
                <el-select :disabled="isDisabled" v-model="dataForm.categoryId" size="small" popper-class="global-select-down" name="categoryId">
                  <el-option
                    :value="0"
                    label="全部" />
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="数据筛选" prop="filter" class="client-type">
              <DataFilter
                ref="DataFilterRef"
                :is-filter="false"
                params-type="id"
                @filterChange="filterChange"/>
            </el-form-item>
            <el-form-item label="已添加字段" prop="field" class="client-type is-required">
              <SelectField
                ref="selectFieldRef"
                :filter-data="filterData"
                @getfilterData="getfilterData"
                @setFieldList="setFieldList" />
            </el-form-item>
          </div>
          <div class="flex-wrap">
            <el-form-item label="排序" prop="sortField" class="">
              <div style="display:flex;">
                <div style="height: 30px;">
                  <el-switch
                    v-model="isSort"
                    class="fb-switch"
                  />
                </div>
                <div v-if="isSort" class="select-sort">
                  <!-- 当前选择的字段 -->
                  <el-select
                    v-model="sortField"
                    placeholder="字段"
                    popper-class="width120 global-select-down"
                    name="sortField"
                    size="small"
                    @change="sortFieldChange">
                    <el-option
                      :value="''"
                      label="请选择" />
                    <el-option
                      v-for="item in fieldListOpt"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </el-select>
                  <el-select
                    v-model="sortType"
                    placeholder="排序"
                    size="small"
                    popper-class="width120 global-select-down"
                    name="sortType">
                    <el-option
                      v-for="item in sortOpt"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </el-select>
                  <el-input
                    v-model.trim="dataForm.showNums"
                    :class="{'showNums-error': showNumsError && !maxNineError, 'max-nine-error': maxNineError}"
                    maxlength="10"
                    max="10"
                    placeholder="展示数量"
                    name="name"
                    type="number"
                    size="small"
                    @blur="inputBlur"/>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="自动更新" prop="timing">
              <Timing ref="timingComponent" :field-list-opt="fieldListOpt" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import { getReportCategory,
  createCollectReport,
  editCollectReport,
  getDetailData
} from '@/api/reportManage';

import Title from '@/components/Title';
import SelectField from '@/components/ReportManage/selectField/index';
import DataFilter from '@/components/ReportManage/dataFilter/index';
import Timing from '@/components/ReportManage/timing';
import { mapState } from 'vuex';

export default {
  name: 'CreateBaseReport',
  components: { Title, SelectField, DataFilter, Timing },
  data() {
    return {
      filterData: [],
      btnLoading: false,
      isEdit: false,
      categoryList: [],
      fieldList: [],
      detailData: null,
      sortOpt: [{ id: 1, name: '正序' }, { id: 2, name: '倒序' }],
      isSort: false,
      dataForm: {
        name: '',
        categoryId: '',
        field: [],
        filter: [],
        dataFilter: [],
        fieldOption: {},
        showNums: ''
      },
      sortField: '',
      sortType: '',
      sortFieldName: '',
      formRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写报表名称' }],
        categoryId: [{ required: true, trigger: 'change', message: '请选择报表分类' }]
      },
      categoryId: '',
      showNumsError: false,
      maxNineError: false,
      isMessage: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isDisabled() {
      return !this.isQuote && (this.isEdit || (this.categoryId !== ''));
    },
    fieldListOpt() {
      const list = this.fieldList.map(i => {
        const obj = {
          name: i.name,
          id: i.id || i.fieldId
        };
        if (i.sourceData) {
          obj.sourceData = i.sourceData;
        }
        return obj;
      }).filter(i => i.name);
        // 临时字段
      if (this.$refs.selectFieldRef) {
        const combFieldsParams = this.$refs.selectFieldRef.getCombFieldsData();
        const formulaData = combFieldsParams.combFields || []; // 配置
        const formulaList = formulaData.map(i => {
          const obj = {
            name: i.name,
            id: i.name
          };
          return obj;
        }).filter(i => i.name);
        if (formulaList) list.push(...formulaList);
      }
      list.forEach(i => {
        if (!i.id || i.sourceData) {
          i.id = i.name;
          i.sortFieldName = i.name;
        }
      });
      return list;
    }
  },
  created() {
    this.getTab();
    this.reportId = this.$route.params.id || '';
    this.isQuote = Number(this.$route.query.quote);
    if (this.isQuote === 1) {
      this.title = '新建汇总报表';
      this.isEdit = true;
      this.getDetailData();
    } else {
      if (this.reportId && this.reportId !== '') {
        this.title = '编辑汇总报表';
        this.isEdit = true;
        this.getDetailData();
      } else {
        this.title = '新建汇总报表';
        this.isEdit = false;
      }
    }
    const categoryId = this.$route.query.categoryId;
    this.categoryId = categoryId;
    if (categoryId) {
      this.dataForm.categoryId = categoryId === 'all' ? 0 : Number(categoryId);
    }
  },
  methods: {
    setFieldList(list) {
      this.fieldList = list;
      if (this.sortField !== '') {
        const ids = this.fieldListOpt.map(i => i.id || i.fieldId);
        if (!ids.includes(this.sortField)) {
          this.sortField = '';
        }
      }
    },
    async getDetailData() {
      try {
        const params = { id: this.reportId, sheetId: 0 };
        const res = await getDetailData(params);
        if (res.data) {
          this.detailData = res.data;
          this.dataForm.name = res.data.name;
          this.dataForm.categoryId = res.data.categoryId || 0;
          this.dataForm.field = res.data.field;
          this.dataForm.showNums = res.data.showNums || '';
          if (res.data.sheetId) this.dataForm.sheetId = res.data.sheetId;
          this.sortField = res.data.sortField;
          this.sortType = res.data.sortType;
          if (res.data.sortFieldName && res.data.sortFieldName !== '') {
            this.sortField = res.data.sortFieldName;
            this.sortFieldName = res.data.sortFieldName;
          }
          this.$refs.selectFieldRef.setDefaultField(res.data.field);
          this.$refs.DataFilterRef.setDefault(res.data.chartFilter);
          this.isMessage = res.data.isRegularUpload;
          if (this.$refs.timingComponent) this.$refs.timingComponent.setDefault(res.data);
          if (this.sortField && this.sortField !== '') {
            this.isSort = true;
          } else {
            this.isSort = false;
          }
        }
        // 引用 清空
        if (this.isQuote === 1) {
          this.dataForm.name = this.dataForm.categoryId = '';
        }
      } catch (error) {
        console.error(error);
      }
    },
    async getTab() {
      try {
        const res = await getReportCategory();
        if (res.data) {
          this.categoryList = res.data;
        }
      } catch (error) {
        console.error(error);
      }
    },
    getfilterData() {
      const filterList = this.$refs.DataFilterRef.getParamsData(); // 数据筛选
      this.filterData = [];
      if (filterList && filterList.report && filterList.report.length > 0) {
        this.filterData = this.filterData.concat(filterList.report);
      }
      if (filterList && filterList.system && filterList.system.length > 0) {
        this.filterData = this.filterData.concat(filterList.system);
      }
    },
    toSubmit() {
      try {
        const dataForm = this.dataForm;
        const selectField = this.$refs.selectFieldRef.checkList; // 选择的字段
        const selectRadioList = this.$refs.selectFieldRef.radioList; // 关联字段
        const filterList = this.$refs.DataFilterRef.getParamsData() || null; // 数据筛选

        dataForm.field = selectField.map(i => {
          const obj = {
            fieldId: i.id || i.fieldId,
            fieldName: i.name,
            isFx: i.isFx,
            sourceId: i.sourceId === '' ? 0 : i.sourceId
          };
          if (i.sourceData) obj.sourceData = i.sourceData;
          return obj;
        });
        let mustField = {};
        if (selectRadioList && selectRadioList.id) {
          mustField = {
            fieldId: selectRadioList.id,
            fieldName: selectRadioList.name,
            isFx: selectRadioList.isFx,
            sourceId: selectRadioList.sourceId === '' ? 0 : selectRadioList.sourceId
          };
          if (selectRadioList.sourceData) mustField.sourceData = selectRadioList.sourceData;
          dataForm.field.unshift(mustField);
        }
        /** 公式字段 */
        const combFieldsParams = this.$refs.selectFieldRef.getCombFieldsData();
        dataForm.isSave = combFieldsParams.isSave || false;
        dataForm.combFields = combFieldsParams.combFields || []; // 配置
        /** 公式字段 end */

        const repeatFilter = {};
        let repeatFlag = false;
        if (filterList && filterList.report) {
          filterList.report.forEach(i => {
            if (i.type === 1 && i.field !== '' && i.operation !== '' && i.value !== '') {
              if (repeatFilter[i.type + i.field + i.operation + i.value]) {
                repeatFlag = true;
              } else {
                repeatFilter[i.type + i.field + i.operation + i.value] = 1;
              }
            }
            if (i.type === 1 && i.value === '') {
              i.value = '[]';
            }
          });
          if (repeatFlag) {
            this.$message({ type: 'warning', message: '数据筛选不能重复' });
            return;
          }
        }
        if (filterList) {
          dataForm.chartFilter = [filterList]; // 数据筛选
        }
        if (this.isSort) {
          if (this.sortFieldName !== '') {
            dataForm.sortField = '';
            dataForm.sortFieldName = this.sortFieldName;
          } else {
            dataForm.sortField = this.sortField;
          }
          dataForm.sortType = this.sortType;
          if (dataForm.showNums && dataForm.showNums !== '' && (dataForm.showNums.toString().indexOf('.') >= 0 || Number(dataForm.showNums) <= 0 || Number(dataForm.showNums) > 1000000000)) {
          // this.$message.error('展示数量请输入正整数');
            this.showNumsError = true;
            return;
          } else {
            this.showNumsError = false;
          }
          if (dataForm.showNums !== '' && Number(dataForm.showNums) > 1000000000) {
            this.maxNineError = true;
            return;
          } else {
            this.maxNineError = false;
          }
          if (!dataForm.sortField) {
            dataForm.sortField = null;
          }
        } else {
          dataForm.sortField = null;
          dataForm.sortType = null;
          dataForm.showNums = null;
        }
        dataForm.field = this.removeRepeat(dataForm.field);
        // dataForm.combFields = this.removeRepeatCombFields(dataForm.combFields, dataForm.field);
        this.$refs['editResouceForm'].validate((valid) => {
          if (valid) {
            if (!mustField.fieldId || dataForm.fieldId === '') {
              this.$message({ type: 'warning', message: '请选择关联字段' });
              return;
            }
            // 判断是否每个字段都选择了 sourceId
            const isSourceIdError = dataForm.field.some(i => {
              if (i.isFx === 1) {
                return i.sourceId === 0;
              } else {
                return false;
              }
            });
            if (isSourceIdError) {
              this.$message({ type: 'warning', message: '请为已选择的字段选择来源' });
              return;
            }
            // 获取并验证定时更新
            const timingComponent = this.$refs.timingComponent;
            if (timingComponent) {
              const timingParams = timingComponent.getParams(true);
              if (!timingParams) {
                return;
              }
              Object.assign(dataForm, timingParams);
            }

            if (!this.isEdit || this.isQuote === 1) {
              this.createReport(dataForm);
            } else {
              if (this.isMessage) {
                this.$confirm('自动更新已开始导入数据，若修改字段或频率则以往数据无法更新，请确认修改！', '', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  center: true,
                  type: 'warning',
                  customClass: 'del-message del-message-cancel',
                  iconClass: 'del-icon'
                }).then(() => {
                  this.editReport(dataForm);
                });
              } else {
                this.editReport(dataForm);
              }
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    createReport(data) {
      this.btnLoading = true;
      createCollectReport(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '新建成功'
          });
          this.toBack();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      }).catch((err) => {
        this.btnLoading = false;
        console.log(err);
        // if (err.message !== '网络错误！请检查网络状态...') {
        //   this.$message.error(err.message);
        // }
      });
    },
    editReport(data) {
      data.reportId = this.reportId;
      this.btnLoading = true;
      editCollectReport(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '编辑成功'
          });
          this.toBack();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      }).catch((err) => {
        this.btnLoading = false;
        console.log(err);
        // if (err.message !== '网络错误！请检查网络状态...') {
        //   this.$message.error(err.message);
        // }
      });
    },
    inputBlur() {
      const dataForm = this.dataForm;
      if (dataForm.showNums !== '' && (dataForm.showNums.toString().indexOf('.') >= 0 || Number(dataForm.showNums) < 0)) {
        this.showNumsError = true;
      } else {
        this.showNumsError = false;
      }
      if (dataForm.showNums !== '' && Number(dataForm.showNums) > 1000000000) {
        this.maxNineError = true;
      } else {
        this.maxNineError = false;
      }
    },
    removeRepeat(data) {
      const hash = {};
      const newArr = data.reduce((item, next) => {
        if (!hash[next.fieldName]) {
          hash[next.fieldName] = item.push(next);
        }
        return item;
      }, []);
      return newArr;
    },
    removeRepeatCombFields(combFields, field) {
      const fieldNameList = field.map(i => i.fieldName);
      const combFieldsData = combFields.filter(i => !fieldNameList.includes(i.name));
      return combFieldsData;
    },
    toBack() {
      this.$router.push({ name: 'total', query: { categoryId: this.categoryId }});
    },
    sortFieldChange(id) {
      if (typeof id === 'string') {
        this.sortFieldName = id;
      } else {
        this.sortFieldName = '';
      }
    },
    keyupEvent(value) {
      let str = value.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^\d*\.\d*\./g, str.substring(0, str.length - 1));// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      if (str.indexOf('.') < 0) {
        if (str.length > 9) {
          str = str.substring(0, str.length - 1);
        }
      } else {
        let integer = str.split('.')[0];
        const decimal = str.split('.')[1];
        if (integer.length > 9) {
          integer = integer.substring(0, integer.length - 1);
          str = integer + '.' + decimal;
        }
      }
      this.dataForm.showNums = str;
    },
    /**
     * 当筛选条件变更是触发，触发时所做的判断
     * 1. 重新获取所有已选择字段的表格列表
     * 2. 并判断当前选中的表格是否在新的表格列表里面存在，不存在则置空 （在 fieldSource 里面判断）
     */
    filterChange(filterList) {
      if (this.$refs.selectFieldRef && this.$refs.selectFieldRef.filterChange) {
        this.$refs.selectFieldRef.filterChange(filterList);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@mixin errorStyle($msg) {
  &.el-input {
    .el-input__inner {
      border-color: #F56C6C;
    }
    &::after {
      content: $msg;
      color: #F56C6C;
      font-size: 12px;
      line-height: 1;
      padding-top: 4px;
      position: absolute;
      top: 100%;
      left: 0;
    }
  }
}
.create-collect-report {
  .report-form {
    margin: 16px;
    background-color: #fff;
    padding: 16px 24px 24px;
    min-height: calc(100vh - 80px);
    .form {
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
      // border-radius:12px;
      // padding-left: 32px;
      // background-color: #fff;
      // padding-right: 32px;
      // padding-bottom: 20px;
    }
  }
  .crm-add-btn {
    margin: 32px 0 0 32px;
  }
  .one-cell {
    display: flex;
    .name {
      margin-right: 51px;
    }
  }
  &::v-deep {
    .showNums-error {
      @include errorStyle('请输入正整数');
    }
    .max-nine-error {
      @include errorStyle('请输入 9 位以内的数值');
    }
  }
}

</style>
<style lang="scss">
.create-collect-report {
  .el-form {
    .el-form-item {
      .el-input__icon {
        line-height: 24px;
      }
      .el-input__inner {
        width: 240px;
        padding: 0 12px 0 8px;
      }
    }
    .contact-list {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .add-btn {
      button {
        width: 501px;
        background-color: #f4f4f4;
        border: 1px dashed #e0e0e0;
        color: #777;
        .add-img {
          margin-right: 8px;
        }
      }
    }
  }
  .flex {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  .select-sort {
    display: inline-block;
    display: flex;
    .el-input {
      width: 120px !important;
      margin-left: 19px;
    }
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.el-select-dropdown.width120 {
  min-width: 120px !important;
}
.mobile-create-collect-report {
  .report-form {
    margin: 12px 12px 150px 12px !important;
    padding: 12px !important;
    border-radius: 6px;
  }
  .one-cell {
    display: block !important;
    ::v-deep {
      .el-select, .el-input {
        width: 100%;
        .el-input__inner {
          width: 100%;
        }
      }
    }
  }
  .form {
    overflow-x: auto;
    .flex-wrap {
      width: 100%;
      margin: 0;
    }
    .delete-btn, .button-text {
      white-space: nowrap;
    }
  }
  .mobile-data-container {
    max-width: 100%;
    overflow-x: auto;
  }
  ::v-deep {
    .el-form-item {
      width: 100%;
    }
  }
}
</style>
